package cn.sciento.iam.saas.domain.service.observer;

import cn.sciento.iam.domain.entity.Tenant;
import cn.sciento.iam.domain.entity.TenantConfig;
import cn.sciento.iam.saas.app.service.TenantConfigService;
import cn.sciento.iam.saas.domain.service.TenantObserver;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Nonnull;
import java.util.List;

public class TenantConfigObserver implements TenantObserver<List<TenantConfig>> {
  private static final Logger LOGGER = LoggerFactory.getLogger(TenantConfigObserver.class);
  
  @Autowired
  private TenantConfigService tenantConfigService;
  
  @Override
  public int order() {
    return 10;
  }
  
  @Override
  public List<TenantConfig> tenantCreate(@Nonnull Tenant tenant) {
    List<TenantConfig> configs = tenant.getTenantConfigs();
    if (CollectionUtils.isNotEmpty(configs)) {
      configs = this.tenantConfigService.createOrUpdateTenantConfigs(tenant.getTenantId(), configs);
    }
    LOGGER.info("[TenantInit - Num={}] -> {}", tenant.getTenantNum(), configs);
    return configs;
  }
  
  @Override
  public List<TenantConfig> tenantUpdate(@Nonnull Tenant tenant) {
    List<TenantConfig> configs = tenant.getTenantConfigs();
    if (CollectionUtils.isNotEmpty(configs)) {
      return this.tenantConfigService.createOrUpdateTenantConfigs(tenant.getTenantId(), configs);
    }
    LOGGER.info("Update tenant config, tenantNum is {}, configs is {}", tenant.getTenantNum(), configs);
    return configs;
  }
}
